package com.czh.intelligentoj.judge.strategy;

import cn.hutool.json.JSONUtil;
import com.czh.intelligentoj.model.dto.question.JudgeCase;
import com.czh.intelligentoj.model.dto.question.JudgeConfig;
import com.czh.intelligentoj.judge.codesandbox.model.JudgeInfo;
import com.czh.intelligentoj.model.entity.Question;
import com.czh.intelligentoj.model.enums.JudageInfoMeaasgeEnum;

import java.util.List;

/*
 * ClassName: DefaultJudgeStrategy
 * Package: com.czh.intelligentoj.judge.strategy
 * Description:
 *              默认判题策略
 * @Author: CZH
 * @Create: 2025
 */
public class JavaJudgeStrategy implements JudgeStrategy {
    @Override
    public JudgeInfo doJudge(JudgeContext judgeContext) {
        //获取判题信息
        JudgeInfo judgeInfo = judgeContext.getJudgeInfo();
        //获取判题后得到的时间、内存
        Long time = judgeInfo.getTime();
        Long memory = judgeInfo.getMemory();
        List<String> inputList = judgeContext.getInputtList();
        List<String> outputList = judgeContext.getOutputList();
        List<JudgeCase> judgeCaseList = judgeContext.getJudgeCaseList();
        Question question = judgeContext.getQuestion();
        JudageInfoMeaasgeEnum judgeInfoMeaasgeEnum = JudageInfoMeaasgeEnum.ACCEPTED;
        JudgeInfo judgeInfoResponse = new JudgeInfo();
        judgeInfoResponse.setMemory(memory);
        judgeInfoResponse.setTime(time);
        //判断输出个数是否与输入个数一致
        if (outputList.size() != inputList.size()) {
            judgeInfoMeaasgeEnum = JudageInfoMeaasgeEnum.WRONG_ANSWER;
            judgeInfoResponse.setMessage(judgeInfoMeaasgeEnum.getValue());
            return judgeInfoResponse;
        }
        //遍历题目判题案例，判断是否全部正确
        for (int i = 0; i < judgeCaseList.size(); i++) {
            if (!judgeCaseList.get(i).getOutput().equals(outputList.get(i))) {
                judgeInfoMeaasgeEnum = JudageInfoMeaasgeEnum.WRONG_ANSWER;
                judgeInfoResponse.setMessage(judgeInfoMeaasgeEnum.getValue());
                return judgeInfoResponse;
            }
        }
        //判断是否超出题目限制
        //获取题目限制配置
        String judgeConfig = question.getJudgeConfig();
        JudgeConfig bean = JSONUtil.toBean(judgeConfig, JudgeConfig.class);
        Long timeLimit = bean.getTimeLimit();
        Long memoryLimit = bean.getMemoryLimit();
        //判断是否超出时间限制
        if (time > timeLimit) {
            judgeInfoMeaasgeEnum = JudageInfoMeaasgeEnum.TIME_LIMIT_ERROR;
            judgeInfoResponse.setMessage(judgeInfoMeaasgeEnum.getValue());
            return judgeInfoResponse;
        }
        //判断是否超出内存限制
        if (memory > memoryLimit) {
            judgeInfoMeaasgeEnum = JudageInfoMeaasgeEnum.MEMORY_LIMIT_ERROR;
            judgeInfoResponse.setMessage(judgeInfoMeaasgeEnum.getValue());
            return judgeInfoResponse;
        }
        //返回结果
        judgeInfoResponse.setMessage(judgeInfoMeaasgeEnum.getValue());
        return judgeInfoResponse;
    }
}
